package com.lmm.cg.zjgcg.pages;


import android.util.Log;

import com.lmm.cg.zjgcg.config.ConfigValue;
import com.lmm.cg.zjgcg.pages.rnplugins.CheckVersionCallBack;
import com.lmm.cg.zjgcg.pages.rnplugins.UploadCallBack;
import com.lmm.cg.zjgcg.service.BasicNameValuePair;
import com.lmm.cg.zjgcg.service.ReturnInfo;
import com.lmm.cg.zjgcg.service.UploadAction;
import com.lmm.cg.zjgcg.service.WSHelper;
import com.lmm.cg.zjgcg.task.BaseTask;
import com.lmm.cg.zjgcg.task.TaskCallBack;
import com.lmm.dresswisdom.lmmframe.retrofit.AppCallBack;
import com.lmm.dresswisdom.lmmframe.retrofit.AppClient;
import com.lmm.dresswisdom.lmmframe.util.FileUtils;
import com.lmm.dresswisdom.lmmframe.util.LogUtils;
import com.lmm.dresswisdom.lmmframe.util.ToastUtils;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.ObservableEmitter;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author xmgong
 * @date 2017/10/31
 * 相关复杂操作
 */

public class ReactNativePresent {


    UploadAction uploadAction;

    /**
     * 上传图片
     *
     * @param token
     * @param filetag
     * @param mfile
     * @param uploadCallBack
     */
    public static void uploadImg(String token, String filetag, File mfile, final UploadCallBack uploadCallBack) {
        UploadManager uploadManager = new UploadManager();
        final String filename = FileUtils.getDateFileName(mfile.getName(), filetag);
        uploadManager.put(mfile, filename, token, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject response) {
                if (info.isOK()) {
                    ToastUtils.showToastShort("上传成功");
                    uploadCallBack.uploadFinish(filename);
                } else {
                    ToastUtils.showToastShort("图片上传失败");
                }
            }
        }, null);
    }

    /**
     * 新羽上传图片接口
     */
    public void uploadFile(final String YeWuGuid, final File mfile, final UploadCallBack uploadCallBack) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<BasicNameValuePair> param = new ArrayList<BasicNameValuePair>();
                param.add(new BasicNameValuePair("FileStream", FileUtils.encodeBase64File(mfile)));
                param.add(new BasicNameValuePair("YeWuGuid", YeWuGuid));
                param.add(new BasicNameValuePair("FileType", "image"));
                String result = WSHelper.GetResponse(ConfigValue.API_Upload_Url, "UploadFile", param);
                LogUtils.write(result);
                if (result == "No") {
                    uploadCallBack.uploadFail();
                } else {
                    uploadCallBack.uploadFinish(ConfigValue.IMG_HEAD_Url + result);
                }

            }
        }).start();

    }


    public void uploadJXCX(final String YeWuGuid, final File mfile, final String refreshToken, final String accessToken, final UploadCallBack uploadCallBack) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<BasicNameValuePair> param = new ArrayList<BasicNameValuePair>();
                param.add(new BasicNameValuePair("FileStream", FileUtils.encodeBase64File(mfile)));
                param.add(new BasicNameValuePair("YeWuGuid", YeWuGuid));
                param.add(new BasicNameValuePair("FileType", "image"));
                param.add(new BasicNameValuePair("PicType", "jpg"));
                param.add(new BasicNameValuePair("RefreshToken", refreshToken));
                param.add(new BasicNameValuePair("AccessToken", accessToken));

                String result = WSHelper.GetResponse(ConfigValue.API_Upload_Url, "test1", param);
                LogUtils.write(result);
                if (result.toLowerCase().equals("no")) {

                    uploadCallBack.uploadFail();
                } else {
                    uploadCallBack.uploadFinish(ConfigValue.IMG_HEAD_Url + result);
                }

            }
        }).start();
    }

    public void uploadJXCX2(final String YeWuGuid, final File mfile, final String type, final UploadCallBack uploadCallBack) {

        new BaseTask<HashMap<String, String>>(new uploadCallback()) {
            @Override
            public void exec(ObservableEmitter emitter) {
                OkHttpClient client = new OkHttpClient();
                MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
                Map<String, String> params = new HashMap<>();
                params.put("FileStream", FileUtils.encodeBase64File(mfile));
                params.put("YeWuGuid", YeWuGuid);
                params.put("FileType", "image");
                params.put("PicType", "jpg");
                params.put("RefreshToken", "");
                params.put("AccessToken", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NzMyODIyODM4NTksInBheWxvYWQiOiJ7XCJpZFwiOlwiMS0xXCIsXCJ1c2VyTmFtZVwiOlwiYWRtaW5cIixcInRydWVOYW1lXCI6XCLns7vnu5_nrqHnkIblkZhcIixcInBob25lXCI6XCJcIixcImRlcHRJZFwiOlwiZDY4MDIzZTAtYWUyZi00N2YzLThlZDQtMjRmNzcyNWM5ZWU0XCIsXCJ0eXBlXCI6bnVsbCxcInN0YXRlXCI6MSxcInBhc3N3b3JkXCI6XCJcIixcInNleFwiOjAsXCJiaXJ0aERheVwiOm51bGwsXCJuYXRpb25cIjpcIlwiLFwicXV5dVwiOlwiXCIsXCJ6aGljaGVuZ1wiOlwiXCIsXCJob21lUGhvbmVcIjpcIlwiLFwiZU1haWxcIjpcIlwiLFwidXNlclB3ZFwiOlwiaUdrbE1UamlPOE10TnhQRHZrQ1Q2S0h1cmRScFNsVkZMRlpMRW9QTVRaVT1cIixcInNhbHRcIjpcImMrMml1a3lLZVM4MFdlYUIvQm5MZVE9PVwiLFwiZ3VhbmxpYW5xdXl1XCI6bnVsbCxcImluZGV4UGFnZVwiOlwiaW5kZXhcIixcImdseUZsYWdcIjoxLFwiYnVtZW5JZFwiOlwiXCIsXCJjYXF5XCI6MCxcImNhXCI6XCJcIixcInFxXCI6bnVsbH0ifQ.lXKGcLsdFxKf5tJFcpDLyEHHe_tKuzI4G2LYugzTDKc");

                RequestBody body = RequestBody.create(mediaType, generateRequestBodyStr(params));
                Request request = new Request.Builder()
                        .url("http://221.224.118.58:5080/zjgszcg_2019/WtzfWebService/QWGLNew.asmx/UploadFile_JYCX")
                        .post(body).build();
                try {
                    Response response = client.newCall(request).execute();
                    Log.d("Eric", response.body().string());

                } catch (IOException e) {

                    e.printStackTrace();
                }

            }
        }.run();
    }

    class uploadCallback extends TaskCallBack<HashMap<String, String>> {

        @Override
        public void onSuccess(HashMap<String, String> stringStringHashMap) {

        }

        @Override
        public void onFail(String s) {

        }

        @Override
        public void onFinish() {

        }
    }


    private String generateRequestBodyStr(Map<String, String> requestDataMap) {
        String bodystr = "";
        for (String key : requestDataMap.keySet()) {
            bodystr += key + "=" + requestDataMap.get(key) + "&";
        }
        return bodystr;
    }

    public void uploadFileJYCX(final String YeWuGuid, final File mfile, final String accessToken, final String refreshToken, final UploadCallBack uploadCallBack) {
        uploadAction = AppClient.getRetrofit("http://221.224.118.58:5080/zjgszcg_2019/WtzfWebService/QWGLNew.asmx").create(UploadAction.class);
        Map<String, String> params = new HashMap<>();
        params.put("FileStream", FileUtils.encodeBase64File(mfile));
        params.put("YeWuGuid", YeWuGuid);
        params.put("FileType", "image");
        params.put("PicType", "jpg");
        params.put("RefreshToken", refreshToken);
        params.put("AccessToken", accessToken);
        AppClient.request(uploadAction.uploadJYCX((params)), new AppCallBack<HashMap<String, Object>>() {
            @Override
            public void onSuccess(HashMap<String, Object> result) {
                String imgId = result.get("image_id").toString();

                Log.i("Eric", imgId);
                ArrayList results = (ArrayList) result.get("results");
                if (results.size() > 0) {
                    uploadCallBack.uploadFinish(ConfigValue.IMG_HEAD_Url + result);
                } else {
                    uploadCallBack.uploadFail();
                }

            }

            @Override
            public void onFailure(String s) {
                uploadCallBack.uploadFail();
            }

            @Override
            public void onFinish() {

            }
        });

        //        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                List<BasicNameValuePair> param = new ArrayList<BasicNameValuePair>();
//                param.add(new BasicNameValuePair("FileStream", FileUtils.encodeBase64File(mfile)));
//                param.add(new BasicNameValuePair("YeWuGuid", YeWuGuid));
//                param.add(new BasicNameValuePair("FileType", "image"));
//                param.add(new BasicNameValuePair("PicType", "jpg"));
//                if (type.equals("jycxPj")) {
////                    param.add(new BasicNameValuePair("PicType", "票据"));
//                } else {
////                    param.add(new BasicNameValuePair("PicType", "证据"));
//                }
//
//                String result = WSHelper.GetResponse(ConfigValue.API_Upload_Url, "UploadFile_JYCX", param);
//                LogUtils.write(result);
//                if (result.toLowerCase().equals("no")) {
//
//                    uploadCallBack.uploadFail();
//                } else {
//                    uploadCallBack.uploadFinish(ConfigValue.IMG_HEAD_Url + result);
//                }
//
//            }
//        }).start();
    }


    /**
     * 消息内部图片上传
     *
     * @param YeWuGuid
     * @param mfile
     * @param type
     * @param uploadCallBack
     */
    public void uploadFileMessage(final String YeWuGuid, final File mfile, final String type, final UploadCallBack uploadCallBack) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<BasicNameValuePair> param = new ArrayList<BasicNameValuePair>();
                param.add(new BasicNameValuePair("FileStream", FileUtils.encodeBase64File(mfile)));
                param.add(new BasicNameValuePair("YeWuGuid", YeWuGuid));
                param.add(new BasicNameValuePair("FileType", "image"));
                if (type.equals("ybaj")) {
                    param.add(new BasicNameValuePair("type", "02"));
                } else {
                    param.add(new BasicNameValuePair("type", "04"));
                }

                String result = WSHelper.GetResponse(ConfigValue.API_Upload_Url, "Message_UploadFile", param);
                LogUtils.write(result);
                if (result.toLowerCase().equals("no")) {
                    uploadCallBack.uploadFail();
                } else {
                    uploadCallBack.uploadFinish(ConfigValue.IMG_HEAD_Url + result);
                }

            }
        }).start();
    }

    /**
     * 一般案件
     * 双随机案件
     *
     * @param YeWuGuid
     * @param mfile
     * @param type
     * @param uploadCallBack
     */
    public void uploadFileYBAJ(final String YeWuGuid, final File mfile, final String type, final UploadCallBack uploadCallBack) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<BasicNameValuePair> param = new ArrayList<BasicNameValuePair>();
                param.add(new BasicNameValuePair("FileStream", FileUtils.encodeBase64File(mfile)));
                param.add(new BasicNameValuePair("RowGuid", YeWuGuid));
                param.add(new BasicNameValuePair("FileType", "image"));
                String result = WSHelper.GetResponse(ConfigValue.API_Upload_Url, "YBAJ_TPUpload", param);
                LogUtils.write(result);
                if (result.toLowerCase().equals("no")) {
                    uploadCallBack.uploadFail();
                } else {
                    uploadCallBack.uploadFinish(ConfigValue.IMG_HEAD_Url + result);
                }

            }
        }).start();
    }


    public void uploadOCRCar(final File mfile, final UploadCallBack uploadCallBack) {
        //https://api-cn.faceplusplus.com/imagepp/v1/licenseplate
        uploadAction = AppClient.getRetrofit("https://api-cn.faceplusplus.com/imagepp/v1/").create(UploadAction.class);
        Map<String, String> params = new HashMap<>();
        params.put("api_key", "n9H84vRMI72ox6WFWR0gVlQpphD89oHW");
        params.put("api_secret", "Y0QYTIveb1zNCSFdQ-dhTsjeACxCInfx");
        params.put("image_base64", FileUtils.encodeBase64File(mfile));
        AppClient.request(uploadAction.uploadOCRCar(generateRequestBody(params)), new AppCallBack<HashMap<String, Object>>() {
            @Override
            public void onSuccess(HashMap<String, Object> result) {
                String imgId = result.get("image_id").toString();
                Log.i("Eric", imgId);
                ArrayList results = (ArrayList) result.get("results");
                if (results.size() > 0) {
                    HashMap<String, Object> car = (HashMap<String, Object>) results.get(0);
                    String number = car.get("license_plate_number").toString();
                    Log.i("Eric", number);
                    uploadCallBack.uploadFinish(number);
                } else {
                    uploadCallBack.uploadFail();
                }

            }

            @Override
            public void onFailure(String s) {
                uploadCallBack.uploadFail();
            }

            @Override
            public void onFinish() {

            }
        });
    }


    public void uploadOCRPerson(final File mfile, final UploadCallBack uploadCallBack) {
        uploadAction = AppClient.getRetrofit("https://api-cn.faceplusplus.com/cardpp/v1/").create(UploadAction.class);
        Map<String, String> params = new HashMap<>();
        params.put("api_key", "n9H84vRMI72ox6WFWR0gVlQpphD89oHW");
        params.put("api_secret", "Y0QYTIveb1zNCSFdQ-dhTsjeACxCInfx");
        params.put("image_base64", FileUtils.encodeBase64File(mfile));
        AppClient.request(uploadAction.uploadOCRPerson(generateRequestBody(params)), new AppCallBack<HashMap<String, Object>>() {
            @Override
            public void onSuccess(HashMap<String, Object> result) {
                String imgId = result.get("image_id").toString();
                Log.i("Eric", imgId);
                ArrayList results = (ArrayList) result.get("cards");
                if (results.size() > 0) {
                    HashMap<String, Object> car = (HashMap<String, Object>) results.get(0);
                    String number = car.get("id_card_number").toString();
                    String name = car.get("name").toString();
                    uploadCallBack.uploadFinish(number + ";" + name);
                } else {
                    uploadCallBack.uploadFail();
                }
            }

            @Override
            public void onFailure(String s) {
                uploadCallBack.uploadFail();
            }

            @Override
            public void onFinish() {

            }
        });
    }

    /**
     * 检测更新
     */
    public void checkVersion(CheckVersionCallBack callBack) {
        uploadAction = null;
        uploadAction = AppClient.getRetrofit(ConfigValue.API_Url).create(UploadAction.class);
        Map<String, String> params = new HashMap<>();
        params.put("SystemType", "android");
        AppClient.request(uploadAction.getVersion(params), new AppCallBack<ReturnInfo<HashMap<String, String>>>() {
            @Override
            public void onSuccess(ReturnInfo<HashMap<String, String>> maps) {
                LogUtils.write(maps.toString());
            }

            @Override
            public void onFailure(String s) {
                LogUtils.write(s);
            }

            @Override
            public void onFinish() {
                LogUtils.write("finish");
            }
        });
    }


    private static Map<String, RequestBody> generateRequestBody(Map<String, String> requestDataMap) {
        Map<String, RequestBody> requestBodyMap = new HashMap<>();
//        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        for (String key : requestDataMap.keySet()) {
//            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),
//                    requestDataMap.get(key) == null ? "" : requestDataMap.get(key));

            RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), requestDataMap.get(key) == null ? "" : requestDataMap.get(key));

            requestBodyMap.put(key, requestBody);
        }
        return requestBodyMap;
    }

}
